package cn.fl.rebacc.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.fl.mfr.web.service.IMfrBankAccService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.product.service.ISplBankService;
import cn.fl.product.service.ISplInfoService;
import cn.fl.product.vo.SplBankVO;
import cn.fl.product.vo.SplInfoVO;
import cn.fl.system.constant.SysLogConstant;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import fl.spl.facade.framework.constant.DictionaryConstant;
import fl.spl.facade.framework.constant.SplRelFlowModTypConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.framework.enums.FlowStartRelInfoCfgEnum;
import fl.spl.facade.spl.constant.SplInfoConstant;

@Controller
@RequestMapping(value = "/commonBankAcc")
public class CommonBankAccInfoController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CommonBankAccInfoController.class);

    @Autowired
    private ISplBankService prdSplBankService;

    @Autowired
    private ISplInfoService splInfoService;
    
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService ;

    @Autowired
    private IMfrBankAccService mfrBankAccService ;

    /**
     * 启动流程
     */
    @RequestMapping(value = "/flow/startAccessFlow.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object startAccessFlow(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("id");
        String procDefKey = request.getParameter("procDefKey");
        String procDefId = request.getParameter("procDefId");
        String procNo = request.getParameter("procNo");
        String modelTyp = request.getParameter("modelTyp");

        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "startAccessFlow", SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY, CurrentThreadContext.getCurrentUserName());
            return result;
        }
        FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
        try {
            //流程定义Key和流程定义ID 如果是前端选择的则直接指定,如果不是则系统自动按照配置选择唯一一条记录,如果找不到会提示
            if (FlowStartRelInfoCfgEnum.isExists(modelTyp, null)) {
                flowStartParamsDTO.setWordsInTheTable(FlowStartRelInfoCfgEnum.getEnumByCode(modelTyp).getWordsInTheTable());
                flowStartParamsDTO.setBusinessType(FlowStartRelInfoCfgEnum.getEnumByCode(modelTyp).getBusinessType());//确认用不用
            } else {
                flowStartParamsDTO.setWordsInTheTable(SplInfoConstant.SPL_FLOW_S_H_SPL);
                flowStartParamsDTO.setBusinessType(FlowConstant.FLOW_BUSINESS_TYP_SPL_BANK_ACC);//确认用不用
            }
            flowStartParamsDTO.setModelTyp(modelTyp);//需要和流程配置中的模块类型匹配
            //flowStartParamsDTO.setModelTyp(FlowConstant.FLOW_MODEL_TYP_SPL_1);//需要和流程配置中的模块类型匹配
            flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
            flowStartParamsDTO.setProcDefKey(procDefKey);
            flowStartParamsDTO.setProcDefId(procDefId);
            flowStartParamsDTO.setProcNo(procNo);
            flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            flowStartParamsDTO.setBusinessKey(id);
            flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
            flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
            flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
            flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
            flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
            flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);//优先级,可以在界面定义
            flowStartParamsDTO.setSearchDesc(CurrentThreadContext.getCurrentOrgDispNm() + "、供应商流程大字段参数未定!");
            DataResultDTO dataResultDTO = this.prdSplBankService.addFlowStart(flowStartParamsDTO);
            if (!dataResultDTO.getCode().equals(BaseExceptionConstant.BASE_EXCEPTION_CODE_200)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
            }
            if (null != dataResultDTO && null != dataResultDTO.getData()) {
                FlowStartedDTO flowStartedDTO = (FlowStartedDTO) dataResultDTO.getData();
                if (StringUtils.isNotBlank(flowStartedDTO.getNextOperUsrNames())) {
                    result.setInfo("下一个节点操作人:" + flowStartedDTO.getNextOperUsrNames());
                } else {
                    result.setInfo("流程发起成功");
                }
            }
        } catch (BaseException e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(e.getMessage());
            BaseLogUtils.info(logger, "addFlowStart", "错误[BaseException],请求参数：" + JSONObject.toJSONString(flowStartParamsDTO) + " -ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
            e.getStackTrace();
        } catch (Exception e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "addFlowStart", "错误[Exception],请求参数：" + JSONObject.toJSONString(flowStartParamsDTO) + " -ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
            e.getStackTrace();
        }
        return result;
    }

    /**
     * 到详情页面
     */
    @RequestMapping(value = "/flow/toDetail.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        String isFlow = request.getParameter("isFlow");//是否流程附加信息页面标识
        BaseLogUtils.info(logger, "toDetailPage", "加载供应商备案账号详情页面.", CurrentThreadContext.getCurrentUserName());

        FlowStartRelInfoCfgEnum cfgEnum = null;
        if (StringUtils.isEmpty(id)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_700, BaseExceptionConstant.BASE_EXCEPTION_CODE_700_NAME);
        } else {
            try {
                cfgEnum = FlowStartRelInfoCfgEnum.fetchEnumByModelTypIdSign(null, id, SplSystemConstant.PK_ID_SUB_STR_BEGIN_INDEX, null);
            }catch (BaseException be){
                cfgEnum = FlowStartRelInfoCfgEnum.FLOW_SPL_ACC ;
                BaseLogUtils.info(logger, "toDetailPage", "账户审核流程业务数据pkId[" + id + "],获取流程配置Eeum报错，be:",be);
            }catch (Exception e){
                cfgEnum = FlowStartRelInfoCfgEnum.FLOW_SPL_ACC ;
                BaseLogUtils.info(logger, "toDetailPage", "账户审核流程业务数据pkId[" + id + "],获取流程配置Eeum报错，e:" ,e);
            }
        }

        ModelAndView view = null;
        String currModelTyp = null;
        if (cfgEnum != null) {
            currModelTyp = cfgEnum.getModelTyp();
            switch (currModelTyp) {
                //经销商账号准入
                case SplRelFlowModTypConstant.SPL_BANK_ACC_ACCESS_MODEL_TYP_CD:
                    view = new ModelAndView("product/splBank/prdSplBankDetail");
                    String splId = "";
                    String splNm = "";
                    if (StringUtils.isNotEmpty(isFlow) && "1".equals(isFlow) && StringUtils.isNotEmpty(id)) {
                        //查询供应商信息
                        SplBankVO splBankVO = this.prdSplBankService.selectById(Long.valueOf(id));
                        if (null != splBankVO && StringUtils.isNotEmpty(splBankVO.getSplId())) {
                            SplInfoVO splInfoVO = this.splInfoService.selectById(splBankVO.getSplId());
                            if (null != splInfoVO && StringUtils.isNotEmpty(splInfoVO.getSplNm())) {
                                splNm = splInfoVO.getSplNm();
                                splId = String.valueOf(splInfoVO.getId());
                            }
                        }
                    }
                    view.addObject("splNm", splNm);
                    view.addObject("splId", splId);
                    view.addObject("id", id);
                    view.addObject("isFlow", isFlow);
                    break;
                //厂商账户审核流程附加页面
                case SplRelFlowModTypConstant.MFR_BANK_ACC_ACCESS_MODEL_TYP_CD:
                	view = new ModelAndView("/mfr/mfrBankAcc/mfrBankAccDetail");
                	view.addObject("id", id);
                	view.addObject("isFlow", BaseConstant.IS_YESNO_YES);
                    break;
                //销售返利账户审核流程附加页面
                case SplRelFlowModTypConstant.SALE_REB_ACC_ACCESS_MODEL_TYP_CD:
                	view = new ModelAndView("rebacc/saleRebAccInfoDetail");
                	view.addObject("id", id);
                    break;
                default:
                    break;
            }
        }

        return view;
    }

    /**
     * 到新增/修改页面
     */
    @RequestMapping(value = "/flow/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        String disable = request.getParameter("disable");//是否只修改用途
        String isFlow = request.getParameter("isFlow");//是否流程附加信息页面标识

        FlowStartRelInfoCfgEnum cfgEnum = null;
        if (StringUtils.isEmpty(id)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_700, BaseExceptionConstant.BASE_EXCEPTION_CODE_700_NAME);
        } else {
            try {
                cfgEnum = FlowStartRelInfoCfgEnum.fetchEnumByModelTypIdSign(null, id, SplSystemConstant.PK_ID_SUB_STR_BEGIN_INDEX, null);
            }catch (BaseException be){
                cfgEnum = FlowStartRelInfoCfgEnum.FLOW_SPL_ACC ;
                BaseLogUtils.info(logger, "toModifyPage", "账户审核流程业务数据pkId[" + id + "],获取流程配置Eeum报错，be:",be);
            }catch (Exception e){
                cfgEnum = FlowStartRelInfoCfgEnum.FLOW_SPL_ACC ;
                BaseLogUtils.info(logger, "toModifyPage", "账户审核流程业务数据pkId[" + id + "],获取流程配置Eeum报错，e:" ,e);
            }
        }

        ModelAndView view = null;
        String currModelTyp = null;
        List<KeyValueVO> bizTypCdList = null ;
        List<KeyValueVO> purpCdList = null ;
        if (cfgEnum != null) {
            currModelTyp = cfgEnum.getModelTyp();
            switch (currModelTyp) {
                //经销商账号准入
                case SplRelFlowModTypConstant.SPL_BANK_ACC_ACCESS_MODEL_TYP_CD:
                    view = new ModelAndView("product/splBank/prdSplBankAdd");
                    String splNm = "";
                    String splId = null;
                    if (StringUtils.isNotEmpty(isFlow) && BaseConstant.IS_YESNO_YES_STR.equals(isFlow) && StringUtils.isNotEmpty(id)) {
                        //查询供应商信息
                        SplBankVO splBankVO = this.prdSplBankService.selectById(Long.valueOf(id));
                        if (null != splBankVO && StringUtils.isNotEmpty(splBankVO.getSplId())) {
                            SplInfoVO splInfoVO = this.splInfoService.selectById(splBankVO.getSplId());
                            if (null != splInfoVO && StringUtils.isNotEmpty(splInfoVO.getSplNm())) {
                                splNm = splInfoVO.getSplNm();
                                splId = String.valueOf(splInfoVO.getId());
                            }
                        }

                    }
                    view.addObject("splNm", splNm);
                    bizTypCdList = this.prdSplBankService.searchBizTypCdList();
                    purpCdList = this.prdSplBankService.searchPurpCdList();
                    view.addObject("bizTypCdList", bizTypCdList);
                    view.addObject("purpCdListJSON", JSON.toJSON(purpCdList));
                    view.addObject("splId", splId);
                    view.addObject("id", id);
                    view.addObject("isFlow", isFlow);
                    view.addObject("disable", disable);
                    view.addObject("currOrgCd", CurrentThreadContext.getCurrentOrgCd());
                    BaseLogUtils.info(logger, "toModifyPage", "加载供应商备案账号新增/修改页面.", CurrentThreadContext.getCurrentUserName());

                    break;
                //厂商账户审核流程附加页面
                case SplRelFlowModTypConstant.MFR_BANK_ACC_ACCESS_MODEL_TYP_CD:
                	view = new ModelAndView("/mfr/mfrBankAcc/mfrBankAccAdd");
                    bizTypCdList = this.mfrBankAccService.searchBizTypCdList();
                    purpCdList = this.mfrBankAccService.searchPurpCdList();
                    view.addObject("bizTypCdList", bizTypCdList);
                    view.addObject("purpCdListJSON", JSON.toJSON(purpCdList));
                	view.addObject("id", id);
                	view.addObject("isFlow",isFlow);
                    break;
                //销售返利账户审核流程附加页面
                case SplRelFlowModTypConstant.SALE_REB_ACC_ACCESS_MODEL_TYP_CD:
                	view = new ModelAndView("rebacc/saleRebAccInfoAdd");
                	List<KeyValueVO> bizTypCdList1 = this.sysDictionaryApiService.getKvList(DictionaryConstant.CODE_BIZ_TYP_CD,
                			SplSystemConstant.FL_SYS_CD,
                			SplSystemConstant.DEFAULT_ORG_CD);
            		view.addObject("bizTypCdList", bizTypCdList1);
            		List<KeyValueVO> purpCdList1 = this.sysDictionaryApiService.getKvList(DictionaryConstant.SALE_ACC_PURP_CD,
            				SplSystemConstant.SPL_SYS_CD,
            				SplSystemConstant.DEFAULT_ORG_CD);
            		view.addObject("purpCdList", purpCdList1);
            		view.addObject("isButton", 1);
            		view.addObject("id", id);
                    break;
                default:
                    break;
            }
        }

        return view;
    }

}
